package com.zr.task.utils;

import android.os.Environment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FilesUtils {
    public static final String pathCrash = Environment.getExternalStorageDirectory().getAbsolutePath() + "/shutdown/";


    private static final long maxFile = 53687091200L; //50M

    public static String readSaveFile(String filePath) {
        FileInputStream inputStream;
        StringBuilder sb = new StringBuilder("");
        try {
            inputStream = new FileInputStream(filePath);
            byte temp[] = new byte[1024];

            int len = 0;
            while ((len = inputStream.read(temp)) > 0) {
                sb.append(new String(temp, 0, len));
            }
            inputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }


    public static void saveCrashInfo2File(String error) {
        try {
            long timestamp = System.currentTimeMillis();
            String time = TimeUtils.getDateToString(timestamp, "yyyy-MM-dd HH:mm:ss");
            String fileName = "shutdown-" + time + "-" + timestamp + ".txt";
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File dir = new File(pathCrash);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(pathCrash + fileName);
                fos.write(error.getBytes());
                fos.close();
            }

        } catch (Exception e) {

        }
    }

    public static boolean deleteFile(File dirFile) {
        // 如果dir对应的文件不存在，则退出
        if (!dirFile.exists()) {
            return false;
        }

        if (dirFile.isFile()) {
            return dirFile.delete();
        } else {

            for (File file : dirFile.listFiles()) {
                deleteFile(file);
            }
        }

        return dirFile.delete();
    }


}
